package cn.xfdzx.android.apps.shop.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.ShopActivity;
import cn.xfdzx.android.apps.shop.activity.XFDGoodsDeatailsActivity;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.MarketGoodsAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpFragment;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.FoundGoodContentBeen;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.MarketBottomContract;
import cn.xfdzx.android.apps.shop.evenbus.HomeFlushCarData;
import cn.xfdzx.android.apps.shop.evenbus.UpdateCarNumMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMarketBottomMessage;
import cn.xfdzx.android.apps.shop.presenter.MarketBottomPresenter;
import cn.xfdzx.android.apps.shop.util.ItemOffsetDecoration;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.UtilsData;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

public class MarketViewPageFragment extends BaseMvpFragment<MarketBottomPresenter> implements MarketBottomContract.View {


    RecyclerView rvMarketGoods;

    private List<FoundGoodContentBeen.DataBean> mGoodList = new ArrayList<>();

    private MarketGoodsAdapter marketGoodsAdapter;
    private String select_id = "";
    private int page = 1;
    private int limit = Constants.LIMIT;
    SmartRefreshLayout mRefreshLayout;
    private LinearLayout ll_hint;

    @Override
    protected void initView(View view) {
        EventBus.getDefault().register(this);
        mPresenter = new MarketBottomPresenter();
        mPresenter.attachView(this);
        select_id = getArguments().getString("select_id");
        findViewInit(view);

//        page = 1;
//        mPresenter.initContent(true, false, select_id, page + "", limit + "");
    }

    private void findViewInit(View view) {
        ll_hint = view.findViewById(R.id.ll_hint);
        rvMarketGoods = view.findViewById(R.id.rv_found_good);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        rvMarketGoods.setLayoutManager(mLayoutManager);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(getContext(), R.dimen.item_offset);
        rvMarketGoods.addItemDecoration(itemDecoration);
        rvMarketGoods.setNestedScrollingEnabled(false);
        marketGoodsAdapter = new MarketGoodsAdapter(getActivity(), mGoodList, mPresenter);
        marketGoodsAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Intent intent = new Intent(getContext(), XFDGoodsDeatailsActivity.class);
                intent.putExtra("good_id", mGoodList.get(position).getId() + "");
                startActivity(intent);
            }
        });
        rvMarketGoods.setAdapter(marketGoodsAdapter);
    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXX(UpdateMarketBottomMessage messageEvent) {
        mGoodList.clear();
//        marketGoodsAdapter.notifyDataSetChanged();
        page = 1;
        select_id=messageEvent.getMessage();
        mPresenter.initContent(true, true, messageEvent.getMessage(), page + "", limit + "");
        mRefreshLayout.setNoMoreData(false);


    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_retail_found_good;
    }

    @Override
    public void showLoading() {
        if (TYPE_IS_RETAIL == 1) {
            if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
                ProgressDialog.getInstance().show(getActivity());
            }
        }
    }

    @Override
    public void hideLoading() {
        if (TYPE_IS_RETAIL == 1) {
            ProgressDialog.getInstance().dismiss();
        }
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean, int position, int total_num) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

            mGoodList.get(position).setAdd_cart_num(total_num);
            marketGoodsAdapter.notifyDataSetChanged();
            Toast.makeText(getActivity(), "加入购物车成功", Toast.LENGTH_SHORT).show();
            UtilsData.getPreference(getActivity(), "carCount").put("car_pf_count", bean.getData().getCount().getPfcount());
            EventBus.getDefault().post(new UpdateCarNumMessage());
//            EventBus.getDefault().post(new HomeFlushCarData());
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroyView();
    }

    @Override
    public void onInitContentSuccess(FoundGoodContentBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mGoodList.clear();
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.initContent(false, false, select_id, page + "", limit + "");
                    }
                });
            }
            if (bean.getData().size() == 0) {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
            }
            mGoodList.addAll(bean.getData());
            if (mGoodList.size() == 0) {
                ll_hint.setVisibility(View.VISIBLE);
            } else {
                ll_hint.setVisibility(View.GONE);
            }
            marketGoodsAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    public static MarketViewPageFragment newInstance(String userUid) {
        Bundle bundle = new Bundle();
        MarketViewPageFragment fragment = new MarketViewPageFragment();
        bundle.putString("select_id", userUid);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }
}
